package com.promise.jokerdream.ui.settings

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.navigation.NavController
import androidx.lifecycle.viewmodel.compose.viewModel
import com.promise.jokerdream.R
import com.promise.jokerdream.navigation.AppRoute
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.viewmodel.SettingsViewModel
import com.promise.jokerdream.work.OneClickPlayExecutor
import com.promise.jokerdream.work.OneClickPlayResult
import com.promise.jokerdream.work.IWork
import com.promise.jokerdream.work.signin.newact.ScratchCardWork
import com.promise.jokerdream.work.penguin.AbyssWork
import com.promise.jokerdream.work.penguin.PenguinFightAutoWork
import com.promise.jokerdream.work.signin.after.ChaosWarWork
import com.promise.jokerdream.work.penguin.PenguinEscortWork
import com.promise.jokerdream.work.penguin.ConstellationWork
import com.promise.jokerdream.work.penguin.MistyWork
import com.promise.jokerdream.work.faction.FactionFeedDemoWork
import com.promise.jokerdream.work.faction.FactionCommerceWork
import com.promise.jokerdream.work.signup.AscendHeavenWork
import com.promise.jokerdream.work.signup.WulinWork
import com.promise.jokerdream.work.penguin.PenguinWlmzWork
import com.promise.jokerdream.work.mercenary.MercenaryDispatchWork
import com.promise.jokerdream.work.penguin.ImmortalsWork
import com.promise.jokerdream.work.knight.lnn.KnightLnnWork
import com.promise.jokerdream.work.signin.WorldTreeWork
import com.promise.jokerdream.work.penguin.PenguinArenaWork
import com.promise.jokerdream.work.knight.Arena.KnightArenaWork
import com.promise.jokerdream.work.team.sect.SectWork
import com.promise.jokerdream.work.team.sect.SectTournamentWork
import com.promise.jokerdream.work.mercenary.MercenaryFormationWork
import com.promise.jokerdream.work.penguin.CurrencyExchangeWork
import com.promise.jokerdream.work.signin.dream.DreamTripWork
import com.promise.jokerdream.work.signin.PenguinTravelogueWork
import com.promise.jokerdream.work.faction.FactionChallengeWork
import com.promise.jokerdream.work.penguin.ScrollDungeonWork
import com.promise.jokerdream.work.faction.FactionAltarWork
import com.promise.jokerdream.work.faction.FactionMineWork
import com.promise.jokerdream.work.penguin.PenguinRecallWork
import com.promise.jokerdream.work.signin.before.ApprenticeWork
import com.promise.jokerdream.work.penguin.PenguinExperienceWork
import com.promise.jokerdream.work.knight.island.KnightIslandWork
import com.promise.jokerdream.model.formation.attrMap
import com.promise.jokerdream.model.formation.FormationSelection
import com.promise.jokerdream.model.swordfight.SwordFightKnightItem
import com.promise.jokerdream.ui.theme.AppFontSizes
import kotlinx.coroutines.launch

/**
 * 设置页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsPage(
    modifier: Modifier = Modifier,
    navController: NavController? = null,
    viewModel: SettingsViewModel = viewModel()
) {
    val account by viewModel.account.collectAsState()
    val userConfig by viewModel.userConfig.collectAsState()
    
    // 防重入机制：跟踪执行状态
    var isExecuting by remember { mutableStateOf(false) }
    
    // 一键代玩执行器
    val oneClickPlayExecutor = OneClickPlayExecutor()
    
    // 执行单个工作的函数
    val executeSingleWork: (IWork) -> Unit = { work ->
        val result = oneClickPlayExecutor.executeSingleWork(work)
        when (result) {
            is OneClickPlayResult.Success -> {
                // 直接替换当前页面为日志页面
                navController?.navigate(AppRoute.ExecutionLog.route)
            }
            is OneClickPlayResult.Failure -> {
                // 可以在这里添加错误提示
                result.exception.printStackTrace()
            }
        }
    }
    
    // 一键代玩执行函数
    val executeOneClickPlay: () -> Unit = {
        // 防重入检查
        if (!isExecuting) {
            val currentAccount = account
            val currentUserConfig = userConfig
            if (currentAccount != null && currentUserConfig != null) {
                // 设置执行状态
                isExecuting = true

                // 使用协程作用域执行suspend函数
                kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                    try {
                        val result = oneClickPlayExecutor.executeOneClickPlay(currentAccount.userId, currentUserConfig)

                        when (result) {
                            is OneClickPlayResult.Success -> {
                                // 直接替换当前页面为日志页面
                                navController?.let { nav ->
                                    nav.popBackStack()
                                    nav.navigate(AppRoute.ExecutionLog.route)
                                }
                            }
                            is OneClickPlayResult.Failure -> {
                                // 可以在这里添加错误提示
                                result.exception.printStackTrace()
                            }
                        }
                    } finally {
                        // 重置执行状态
                        isExecuting = false
                    }
                }
            }
        }
    }
    
    // 如果账户为空，显示空页面
    if (account == null || userConfig == null) {
        return EmptyAccountPage()
    }
    
    // 安全地获取非空配置
    val safeUserConfig = userConfig!!
    val safeUserId = account?.userId!!
    
    // 防重入的返回标志
    val hasPopBack = remember { mutableStateOf(false) }
    
    // 防重入的返回函数
    fun handleBack() {
        if (!hasPopBack.value) {
            hasPopBack.value = true
            navController?.popBackStack()
        }
    }
    
    // 处理返回手势
    BackHandler {
        handleBack()
    }
    
    
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 统一的顶部导航栏
        AppTopBar(
            title = "代玩设置",
            onBackClick = { handleBack() }
        )
        
        // 设置列表
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .background(AppColors.PageBackground),
            contentPadding = PaddingValues(vertical = AppSpacing.listContentPadding)
        ) {
            // 刮刮卡
            item {
                ScratchSettingCard(
                    config = safeUserConfig.gameConfig.scratchConfig,
                    onScratchChange = { 
                        viewModel.updateScratchConfig(enabledSetting = it)
                    },
                    onDailyScratchChange = { 
                        viewModel.updateScratchConfig(dailyScratchEnabled = it)
                    },
                    onHourlyScratchChange = { 
                        viewModel.updateScratchConfig(hourlyScratchEnabled = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(ScratchCardWork(safeUserId))
                    }
                )
            }

            // 深渊之潮
            item {
                AbyssSettingCard(
                    config = safeUserConfig.gameConfig.abyssConfig,
                    onAbyssChange = { 
                        viewModel.updateAbyssConfig(enabledSetting = it)
                    },
                    onWishPointsChange = { 
                        viewModel.updateAbyssConfig(wishPointsEnabled = it)
                    },
                    onExchangeTimesChange = { 
                        viewModel.updateAbyssConfig(exchangeTimesEnabled = it)
                    },
                    onChallengeChange = { 
                        viewModel.updateAbyssConfig(challengeEnabled = it)
                    },
                    onReviveChange = { 
                        viewModel.updateAbyssConfig(reviveEnabled = it)
                    },
                    onAbyssTextChange = { 
                        viewModel.updateAbyssConfig(selectedAbyssText = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(AbyssWork(safeUserConfig.gameConfig.abyssConfig, safeUserId))
                    }
                )
            }

            // 乐斗
            item {
                PenguinFightSettingCard(
                    config = safeUserConfig.gameConfig.penguinFightConfig,
                    onPenguinFightChange = { 
                        viewModel.updatePenguinFightConfig(enabledSetting = it)
                    },
                    onBossChange = { 
                        viewModel.updatePenguinFightConfig(bossEnabled = it)
                    },
                    onXialvChange = { 
                        viewModel.updatePenguinFightConfig(xialvEnabled = it)
                    },
                    onShituChange = { 
                        viewModel.updatePenguinFightConfig(shituEnabled = it)
                    },
                    onJiebaiChange = { 
                        viewModel.updatePenguinFightConfig(jiebaiEnabled = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(PenguinFightAutoWork(safeUserConfig.gameConfig.penguinFightConfig, safeUserId))
                    }
                )
            }

            // 乱斗
            item {
                ChaosWarSettingCard(
                    config = safeUserConfig.gameConfig.chaosWarConfig,
                    onChaosWarChange = { 
                        viewModel.updateChaosWarConfig(enabledSetting = it)
                    },
                    onTasksChange = { 
                        viewModel.updateChaosWarConfig(selectedTasks = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(ChaosWarWork(safeUserId))
                    }
                )
            }

        // 押镖
        item {
            PenguinEscortSettingCard(
                config = safeUserConfig.gameConfig.escortConfig,
                onEnabledChange = {
                    viewModel.updateEscortConfig(enabledSetting = it)
                },
                onNpcIdsChange = {
                    viewModel.updateEscortConfig(selectedNpcIds = it)
                },
                onStrategyChange = {
                    viewModel.updateEscortConfig(strategy = it)
                },
                onExecuteClick = {
                    executeSingleWork(PenguinEscortWork(safeUserConfig.gameConfig.escortConfig, safeUserId))
                }
            )
        }

            // 十二宫
            item {
                ConstellationSettingCard(
                    config = safeUserConfig.gameConfig.constellationConfig,
                    onConstellationChange = { 
                        viewModel.updateConstellationConfig(enabledSetting = it)
                    },
                    onConstellationTextChange = { 
                        viewModel.updateConstellationConfig(levelName = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(ConstellationWork(safeUserConfig.gameConfig.constellationConfig, safeUserId))
                    }
                )
            }
            
            // 历练
            item {
                ExperienceSettingCard(
                    config = safeUserConfig.gameConfig.experienceConfig,
                    onExperienceChange = { 
                        viewModel.updateExperienceConfig(enabledSetting = it)
                    },
                    onPriorityTypeChange = { 
                        viewModel.updateExperienceConfig(priorityType = it)
                    },
                    onCustomOrderChange = { 
                        viewModel.updateExperienceConfig(customOrder = it)
                    },
                    onVitalityPotionChange = { 
                        viewModel.updateExperienceConfig(useVitalityPotion = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(PenguinExperienceWork(safeUserConfig.gameConfig.experienceConfig, safeUserId))
                    }
                )
            }
            
            
            // 幻境
            item {
                MistySettingCard(
                    config = safeUserConfig.gameConfig.mistyConfig,
                    onMistyChange = { 
                        viewModel.updateMistyConfig(enabledSetting = it)
                    },
                    onMistyTextChange = { 
                        viewModel.updateMistyConfig(selectedMistyText = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(MistyWork(safeUserConfig.gameConfig.mistyConfig, safeUserId))
                    }
                )
            }
            
            // 帮派供奉
            item {
                FactionFeedDemoSettingCard(
                    config = safeUserConfig.gameConfig.factionFeedDemoConfig,
                    onEnabledChange = { 
                        viewModel.updateFactionFeedDemoConfig(enabledSetting = it)
                    },
                    onFeedItemNameChange = { 
                        viewModel.updateFactionFeedDemoConfig(feedItemName = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(FactionFeedDemoWork(safeUserConfig.gameConfig.factionFeedDemoConfig, safeUserId))
                    }
                )
            }
            
            // 商会
            item {
                FactionCommerceSettingCard(
                    config = safeUserConfig.gameConfig.factionCommerceConfig,
                    onChamberOfCommerceChange = { 
                        viewModel.updateFactionCommerceConfig(enabledSetting = it)
                    },
                    onTreasureBoxChange = { 
                        viewModel.updateFactionCommerceConfig(treasureBoxEnabled = it)
                    },
                    onTradingChange = { 
                        viewModel.updateFactionCommerceConfig(tradingEnabled = it)
                    },
                    onTradingRewardsChange = { 
                        viewModel.updateFactionCommerceConfig(selectedTradingRewards = it)
                    },
                    onExchangeChange = { 
                        viewModel.updateFactionCommerceConfig(exchangeEnabled = it)
                    },
                    onExchangeRewardsChange = { 
                        viewModel.updateFactionCommerceConfig(selectedExchangeRewards = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(FactionCommerceWork(safeUserConfig.gameConfig.factionCommerceConfig, safeUserId))
                    }
                )
            }
            
            // 飞升大作战
            item {
                AscendHeavenSettingCard(
                    config = safeUserConfig.gameConfig.ascendHeavenConfig,
                    onAscensionBattleChange = { 
                        viewModel.updateAscendHeavenConfig(enabledSetting = it)
                    },
                    onGameModeChange = { gameMode ->
                        viewModel.updateAscendHeavenConfig(gameMode = gameMode)
                    },
                    onScheduledChallengeChange = { 
                        viewModel.updateAscendHeavenConfig(scheduledChallengeEnabled = it)
                    },
                    onRegistrationTimeChange = { time ->
                        viewModel.updateAscendHeavenConfig(registrationTime = time)
                    },
                    onExecuteClick = {
                        executeSingleWork(AscendHeavenWork(safeUserConfig.gameConfig.ascendHeavenConfig, safeUserId))
                    }
                )
            }
            
            // 武林
            item {
                WulinSettingCard(
                    config = safeUserConfig.gameConfig.wulinConfig,
                    onWulinChange = { 
                        viewModel.updateWulinConfig(enabledSetting = it)
                    },
                    onRegistrationTypeChange = { 
                        viewModel.updateWulinConfig(registrationType = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(WulinWork(safeUserConfig.gameConfig.wulinConfig, safeUserId))
                    }
                )
            }
            
            // 武林盟主
            item {
                WlmzSettingCard(
                    config = safeUserConfig.gameConfig.wlmzConfig,
                    onWlmzChange = { 
                        viewModel.updateWlmzConfig(enabledSetting = it)
                    },
                    onGroundTypeChange = { 
                        viewModel.updateWlmzConfig(groundType = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(PenguinWlmzWork(safeUserConfig.gameConfig.wlmzConfig, safeUserId))
                    }
                )
            }
            
            // 佣兵派遣
            item {
                MercenaryDispatchSettingCard(
                    config = safeUserConfig.gameConfig.mercenaryDispatchConfig,
                    onMercenaryDispatchChange = { 
                        viewModel.updateMercenaryDispatchConfig(enabledSetting = it)
                    },
                    onTaskTypeChange = { 
                        viewModel.updateMercenaryDispatchConfig(selectedTaskTypes = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(MercenaryDispatchWork(safeUserConfig.gameConfig.mercenaryDispatchConfig, safeUserId))
                    }
                )
            }
            
            // 仙武修真
            item {
                ImmortalsSettingCard(
                    config = safeUserConfig.gameConfig.immortalsConfig,
                    onImmortalsChange = { 
                        viewModel.updateImmortalsConfig(enabledSetting = it)
                    },
                    onImmortalTypeChange = { type ->
                        viewModel.updateImmortalsConfig(selectedImmortalType = type)
                    },
                    onExecuteClick = {
                        executeSingleWork(ImmortalsWork(safeUserConfig.gameConfig.immortalsConfig, safeUserId))
                    }
                )
            }
            
            // 侠客岛任务
            item {
                KnightMissionSettingCard(
                    config = safeUserConfig.gameConfig.knightMissionConfig,
                    onKnightMissionChange = { 
                        viewModel.updateKnightMissionConfig(enabledSetting = it)
                    },
                    onRewardsChange = { 
                        viewModel.updateKnightMissionConfig(selectedKnightRewards = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(KnightIslandWork(safeUserConfig.gameConfig.knightMissionConfig, safeUserId))
                    }
                )
            }
            
            // 世界树
            item {
                WorldTreeSettingCard(
                    config = safeUserConfig.gameConfig.worldTreeConfig,
                    onWorldTreeChange = { 
                        viewModel.updateWorldTreeConfig(enabledSetting = it)
                    },
                    onCollectMaterialsChange = { 
                        viewModel.updateWorldTreeConfig(collectMaterialsEnabled = it)
                    },
                    onFeedingChange = { 
                        viewModel.updateWorldTreeConfig(feedingEnabled = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(WorldTreeWork(safeUserId))
                    }
                )
            }
            
            // 侠士
            item {
                KnightLnnSettingCard(
                    config = safeUserConfig.gameConfig.knightConfig,
                    onKnightChange = { 
                        viewModel.updateKnightConfig(enabledSetting = it)
                    },
                    onCollectRewardsChange = { 
                        viewModel.updateKnightConfig(collectRewardsEnabled = it)
                    },
                    onExchangeItemsChange = { 
                        viewModel.updateKnightConfig(exchangeItemsEnabled = it)
                    },
                    onSelectedExchangeItemsChange = { 
                        viewModel.updateKnightConfig(selectedExchangeItems = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(KnightLnnWork(safeUserConfig.gameConfig.knightConfig, safeUserId))
                    }
                )
            }
            
            // 竞技场
            item {
                ArenaSettingCard(
                    config = safeUserConfig.gameConfig.arenaConfig,
                    onArenaChange = { 
                        viewModel.updateArenaConfig(enabledSetting = it)
                    },
                    onScheduledChallengeChange = { 
                        viewModel.updateArenaConfig(scheduledChallengeEnabled = it)
                    },
                    onRegistrationTimeChange = { 
                        viewModel.updateArenaConfig(registrationTime = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(PenguinArenaWork(safeUserConfig.gameConfig.arenaConfig, safeUserId))
                    }
                )
            }

            // 侠士论剑
            item {
                KnightArenaSettingCard(
                    config = safeUserConfig.gameConfig.knightArenaConfig,
                    onEnabledChange = { 
                        viewModel.updateKnightArenaConfig(enabledSetting = it)
                    },
                    onScheduledChallengeChange = { 
                        viewModel.updateKnightArenaConfig(scheduledChallengeEnabled = it)
                    },
                    onRegistrationTimeChange = { 
                        viewModel.updateKnightArenaConfig(registrationTime = it)
                    },
                    onFormationsChange = { formations ->
                        viewModel.updateKnightArenaConfig(formations = formations)
                    },
                    onExecuteClick = {
                        executeSingleWork(KnightArenaWork(safeUserConfig.gameConfig.knightArenaConfig, safeUserId))
                    }
                )
            }
            
            // 门派
            item {
                SectSettingCard(
                    config = safeUserConfig.gameConfig.sectConfig,
                    onSectChange = { 
                        viewModel.updateSectConfig(enabledSetting = it)
                    },
                    onPaidIncenseChange = { 
                        viewModel.updateSectConfig(paidIncenseEnabled = it)
                    },
                    onPaidMemberTrainingChange = { 
                        viewModel.updateSectConfig(paidMemberTrainingEnabled = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(SectWork(safeUserConfig.gameConfig.sectConfig, safeUserId))
                    }
                )
            }
            
            // 门派邀请赛
            item {
                SectTournamentSettingCard(
                    config = safeUserConfig.gameConfig.sectTournamentConfig,
                    onEnabledChange = { 
                        viewModel.updateSectTournamentConfig(enabledSetting = it)
                    },
                    onSetting1ValueChange = { 
                        viewModel.updateSectTournamentConfig(setting1Value = it)
                    },
                    onSetting2ValueChange = { 
                        viewModel.updateSectTournamentConfig(setting2Value = it)
                    },
                    onSetting3ValueChange = { 
                        viewModel.updateSectTournamentConfig(setting3Value = it)
                    },
                    onSetting4ValueChange = { 
                        viewModel.updateSectTournamentConfig(setting4Value = it)
                    },
                    onSetting5ValueChange = { 
                        viewModel.updateSectTournamentConfig(setting5Value = it)
                    },
                    onExecuteClick = {
                        executeSingleWork(SectTournamentWork(safeUserConfig.gameConfig.sectTournamentConfig, safeUserId))
                    }
                )
            }
            
            
            // 佣兵助阵
            item {
                FormationSettingCard(
                    enabled = safeUserConfig.gameConfig.formationConfig.enabledSetting,
                    onEnabledChange = { 
                        viewModel.updateFormationConfig(enabledSetting = it)
                    },
                    onFormationSelect = { type, formation, attr ->
                        viewModel.updateFormationConfig(
                            selectedTypeId = type.id,
                            selectedTypeName = type.name,
                            selectedFormationId = formation.id,
                            selectedFormationName = formation.name,
                            selectedAttrIndex = 0,
                            selectedAttrName = attrMap[attr.type] ?: "未知属性"
                        )
                    },
                    selection = remember(safeUserConfig.gameConfig.formationConfig.selectionJson) {
                        if (safeUserConfig.gameConfig.formationConfig.selectionJson.isEmpty()) {
                            FormationSelection.EMPTY
                        } else {
                            try {
                                val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true; encodeDefaults = true }
                                json.decodeFromString<FormationSelection>(safeUserConfig.gameConfig.formationConfig.selectionJson)
                            } catch (e: Exception) {
                                FormationSelection.EMPTY
                            }
                        }
                    },
                    onExecuteClick = {
                        executeSingleWork(MercenaryFormationWork(safeUserConfig.gameConfig.formationConfig, safeUserId))
                    }
                )
            }
            
            // 货币兑换
            item {
                CurrencyExchangeSettingCard(
                    enabled = safeUserConfig.gameConfig.currencyExchangeConfig.enabledSetting,
                    onEnabledChange = { 
                        viewModel.updateCurrencyExchangeConfig(enabledSetting = it)
                    },
                    selectedAmount = remember(safeUserConfig.gameConfig.currencyExchangeConfig.currencyExchangeAmount) {
                        try {
                            com.promise.jokerdream.model.currency.CurrencyExchangeAmount.valueOf(safeUserConfig.gameConfig.currencyExchangeConfig.currencyExchangeAmount)
                        } catch (e: Exception) {
                            com.promise.jokerdream.model.currency.CurrencyExchangeAmount.HUNDRED
                        }
                    },
                    onAmountChange = { amount ->
                        viewModel.updateCurrencyExchangeConfig(currencyExchangeAmount = amount)
                    },
                    onExecuteClick = {
                        executeSingleWork(CurrencyExchangeWork(safeUserConfig.gameConfig.currencyExchangeConfig, safeUserId))
                    }
                )
            }
            
            // 其他
            item {
                OtherSettingCard(
                    config = safeUserConfig.gameConfig.otherConfig,
                    onOtherChange = { 
                        viewModel.updateOtherConfig(enabledSetting = it)
                    },
                    onDreamTripChange = {
                        viewModel.updateOtherConfig(dreamTripEnabled = it)
                    },
                    onPenguinTravelogueChange = {
                        viewModel.updateOtherConfig(penguinTravelogueEnabled = it)
                    },
                    onFactionChallengeChange = {
                        viewModel.updateOtherConfig(factionChallengeEnabled = it)
                    },
                    onScrollDungeonChange = {
                        viewModel.updateOtherConfig(scrollDungeonEnabled = it)
                    },
                    onFactionAltarChange = {
                        viewModel.updateOtherConfig(factionAltarEnabled = it)
                    },
                    onFactionMineChange = {
                        viewModel.updateOtherConfig(factionMineEnabled = it)
                    },
                    onPenguinRecallChange = {
                        viewModel.updateOtherConfig(penguinRecallEnabled = it)
                    },
                    onApprenticeExperienceChange = {
                        viewModel.updateOtherConfig(apprenticeExperienceEnabled = it)
                    },
                    onExecuteClick = {
                        // 其他设置包含多个工作，这里可以执行一个综合的工作或者分别执行
                        executeSingleWork(ScrollDungeonWork(safeUserConfig.gameConfig.otherConfig, safeUserId))
                    }
                )
            }
            
            // 底部间距
            item {
                Spacer(modifier = Modifier.height(AppSpacing.bottomSafeArea))
            }
        }
        
        // 固定的底部按钮区域
        BottomActionButtons(
            onOneClickPlayClick = executeOneClickPlay,
            onSyncClick = {
                // TODO: 实现同步功能
            },
            onImportClick = {
                // TODO: 实现导入功能
            },
            onShareClick = {
                // TODO: 实现分享功能
            },
            isExecuting = isExecuting
        )
    }
}

/**
 * 底部固定按钮区域
 */
@Composable
private fun BottomActionButtons(
    modifier: Modifier = Modifier,
    onOneClickPlayClick: () -> Unit,
    onSyncClick: () -> Unit,
    onImportClick: () -> Unit,
    onShareClick: () -> Unit,
    isExecuting: Boolean = false,
) {
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface,
        shadowElevation = 8.dp
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(
                    horizontal = AppSpacing.pageHorizontal,
                    vertical = AppSpacing.pageVertical
                )
        ) {
            // 双行按钮布局
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium)
            ) {
                // 左侧功能按钮组
                Row(
                    modifier = Modifier.weight(1f),
                    horizontalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    // 同步按钮
                    IconTextButton(
                        onClick = onSyncClick,
                        icon = painterResource(id = R.drawable.icon_sync),
                        text = "同步",
                        modifier = Modifier.width(48.dp)
                    )
                    
                    // 导入按钮
                    IconTextButton(
                        onClick = onImportClick,
                        icon = painterResource(id = R.drawable.icon_import),
                        text = "导入",
                        modifier = Modifier.width(48.dp)
                    )
                    
                    // 分享按钮
                    IconTextButton(
                        onClick = onShareClick,
                        icon = painterResource(id = R.drawable.icon_share),
                        text = "分享",
                        modifier = Modifier.width(48.dp)
                    )
                }
                
                // 右侧一键代玩按钮（固定宽度）
                Button(
                    onClick = onOneClickPlayClick,
                    enabled = !isExecuting,
                    modifier = Modifier.width(110.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (isExecuting) 
                            AppColors.Error 
                        else 
                            MaterialTheme.colorScheme.primary
                    )
                ) {
                    if (isExecuting) {
                        // 执行中：显示菊花转圈
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            color = AppColors.White,
                            strokeWidth = 2.dp
                        )
                    } else {
                        // 正常状态：显示文字
                        Text(
                            text = "一键代玩",
                            fontSize = AppFontSizes.mediumBody,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
            
            // 底部安全区域
            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .windowInsetsPadding(WindowInsets.navigationBars)
                    .height(0.dp)
            )
        }
    }
}

/**
 * 图标文本按钮组件
 */
@Composable
private fun IconTextButton(
    onClick: () -> Unit,
    icon: Painter,
    text: String,
    modifier: Modifier = Modifier
) {
    TextButton(
        onClick = onClick,
        modifier = modifier.height(60.dp),
        colors = ButtonDefaults.textButtonColors(
            contentColor = MaterialTheme.colorScheme.onSurface
        )
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier.fillMaxWidth()
        ) {
            Icon(
                painter = icon,
                contentDescription = text,
                modifier = Modifier.size(20.dp)
            )
            
            Spacer(modifier = Modifier.height(2.dp))
            
            Text(
                text = text,
                fontSize = 10.sp,
                textAlign = TextAlign.Center,
                color = MaterialTheme.colorScheme.onSurface
            )
        }
    }
}

/**
 * 空账户页面
 */
@Composable
private fun EmptyAccountPage(
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "请先登录账户",
            fontSize = 18.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurface
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(
            text = "您需要先登录账户才能使用设置功能",
            fontSize = AppFontSizes.mediumBody,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            textAlign = androidx.compose.ui.text.style.TextAlign.Center
        )
    }
}
